"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const url_1 = __importDefault(require("url"));
const koa_router_1 = __importDefault(require("koa-router"));
const DBConnectTool_1 = __importDefault(require("../com/DBTool/DBConnectTool"));
const ContentTypeTool_1 = __importDefault(require("../lib/ContentTypeTool"));
const readFromNet_1 = __importDefault(require("../lib/GISServer/Util/readFromNet"));
const path_1 = __importDefault(require("path"));
const configTool_1 = __importDefault(require("../com/configTool"));
const imgMD5_1 = __importDefault(require("../img/imgMD5"));
const DBRoutes = new koa_router_1.default({ prefix: '/DBService' });
DBRoutes
    .get('/ue_layer/(.*)', async (ctx) => {
    let reqUrl = ctx.request.url.replace('/DBService/ue_layer', '');
    let urlObj = url_1.default.parse(reqUrl, true);
    reqUrl = decodeURI(urlObj.pathname);
    const regex = /\/(\d+)\/(\d+)\/(\d+)\.(jpg|jpeg|png)$/;
    if (regex.test(reqUrl)) {
        const match = reqUrl.match(regex);
        const z = parseInt(match[1], 10);
        const x = parseInt(match[2], 10);
        const y = parseInt(match[3], 10);
        const realY = Math.pow(2, z) - y - 1;
        reqUrl = reqUrl.replace(regex, `/${z}/${x}/${realY}.$4`);
    }
    reqUrl = encodeURI(`http://127.0.0.1:${configTool_1.default.baseConfig.httpServerPort}/DBService` + reqUrl);
    console.log('UE规则代理接口：', decodeURI(reqUrl));
    const res = await (0, readFromNet_1.default)({ url: reqUrl });
    let contentType = ContentTypeTool_1.default.getContentType(path_1.default.basename(reqUrl));
    ctx.set('content-type', contentType);
    ctx.body = res[1];
})
    .get('/(.*)', async (ctx) => {
    let reqUrl = ctx.request.url.replace('/DBService/', '');
    let urlObj = url_1.default.parse(reqUrl, true);
    reqUrl = decodeURI(urlObj.pathname);
    let pathItem = reqUrl.split('/');
    if (pathItem?.length) {
        let DBName = pathItem.shift();
        let fullPath = '/' + pathItem.join('/');
        let file;
        let dbTool = await DBConnectTool_1.default.openDB(DBName);
        if (dbTool) {
            if (DBName.endsWith('-Index')) {
                const indexDB = await DBConnectTool_1.default.openDB(DBName);
                const indexInfo = await indexDB.getFileByFullPath(fullPath, false);
                const md5 = indexInfo?.file_md5;
                if (md5) {
                    const dataDBName = DBName.endsWith('-16x16-Index') ? DBName.replace('-16x16-Index', '-') : DBName.replace('-Index', '-');
                    const dbTool = await DBConnectTool_1.default.openDB(dataDBName + md5.substring(0, DBName.endsWith('-16x16-Index') ? 2 : 1));
                    file = await dbTool.getFileByFullPath(fullPath, false);
                }
            }
            else {
                file = await dbTool.getFileByFullPath(fullPath, false);
            }
            if (!file || !file.file_data) {
                const lowReqUrl = reqUrl.toLowerCase();
                if (lowReqUrl.endsWith('.png') || lowReqUrl.endsWith('.jpg') || lowReqUrl.endsWith('.jpeg') || lowReqUrl.endsWith('.webp')) {
                    ctx.status = 200;
                    ctx.body = imgMD5_1.default.transparentBuffer;
                }
                else {
                    ctx.status = 422;
                    ctx.set('content-type', 'application/json;charset=utf-8');
                    ctx.body = JSON.stringify({ message: `资源库【${DBName}】连接成功，但找不到该文件资源，路径：【${fullPath}】` });
                }
            }
            else {
                let contentType = ContentTypeTool_1.default.getContentType(file.file_name);
                file.file_zip === 'gzip' && (ctx.set('Content-Encoding', 'gzip'));
                ctx.set('content-type', contentType);
                ctx.body = file.file_data;
            }
        }
        else {
            ctx.status = 422;
            ctx.set('content-type', 'application/json;charset=utf-8');
            ctx.body = JSON.stringify({ message: `资源库不存在【${DBName}】，请检查 Url` });
            return;
        }
    }
});
exports.default = DBRoutes;
